package net.zhengxinyun.performance.Util;


import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.data.SelectOptionBean;
import net.zhengxinyun.performance.filter.ExamQuestionFilter;
import net.zhengxinyun.performance.filter.RolePerFilter;
import net.zhengxinyun.performance.service.department.DepartmentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.nio.file.FileAlreadyExistsException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Auther: hyp
 * @Date: 2018/11/1 10:43
 */
@Component
public class Util {

    public static String MONTH[] = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
    public static String QUERY="query";
    public static String DEL="del";
    public static String UPDATE="update";
    public static String ADD="add";
    public final  static Map<String,String> MONTH_MAP = new HashMap(){
        {
            put("01","01");
            put("02","02");
            put("03","03");
            put("04","04");
            put("05","05");
            put("06","06");
            put("07","07");
            put("08","08");
            put("09","09");
            put("10","10");
            put("11","11");
            put("12","12");
        }
    };


    public final static Map<String,String> examerMap = new HashMap()
    {
        {
            put("1","县领导");
            put("2","党代表");
            put("3","人大代表");
            put("4","政协委员");
            put("5","企业家代表");
            put("6","城乡代表");
            put("0","无限制");

        }


    };

    public static String[] TOWN_HEAD = {"塘前乡", "葛岭镇", "樟城镇", "城峰镇", "清凉镇",
            "富泉乡", "岭路乡", "赤锡乡", "梧桐镇", "嵩口镇", "洑口乡",
            "盖洋乡", "长庆镇", "东洋乡", "霞拔乡", "同安镇", "大洋镇",
            "盘谷乡", "红星乡", "白云乡", "丹云乡"};
    //本地配置

    public static final   String PATH = "D:/data/";



    @Autowired
    private static DepartmentService departmentService;
    //服务器配置
//    public static final String PATH = "user/temp-rainy/excel";

    /**
     * 乡镇转换
     * @param townDTO
     * @return
     */
   /* public static List<TownEntity> townUtil(TownDTO townDTO) {
        List<TownEntity> list = new ArrayList<>();
        if (StringUtils.isNotBlank(townDTO.getTangQ())) {
            TownEntity tangQ = new TownEntity("塘前乡", townDTO.getTangQ());
            list.add(tangQ);
        }
        if (StringUtils.isNotBlank(townDTO.getBaiY())) {
            TownEntity baiY = new TownEntity("白云乡", townDTO.getBaiY());
            list.add(baiY);
        }
        if (StringUtils.isNotBlank(townDTO.getGeL())) {
            TownEntity geL = new TownEntity("葛岭镇", townDTO.getGeL());
            list.add(geL);
        }
        if (StringUtils.isNotBlank(townDTO.getZhangC())) {
            TownEntity zhangC = new TownEntity("樟城镇", townDTO.getZhangC());
            list.add(zhangC);
        }
        if (StringUtils.isNotBlank(townDTO.getChengF())) {
            TownEntity chengF = new TownEntity("城峰镇", townDTO.getChengF());
            list.add(chengF);
        }
        if (StringUtils.isNotBlank(townDTO.getQingL())) {
            TownEntity qingL = new TownEntity("清凉镇", townDTO.getQingL());
            list.add(qingL);
        }
        if (StringUtils.isNotBlank(townDTO.getFuQ())) {
            TownEntity fuQ = new TownEntity("福泉镇", townDTO.getFuQ());
            list.add(fuQ);
        }
        if (StringUtils.isNotBlank(townDTO.getLingL())) {
            TownEntity lingL = new TownEntity("岭路乡", townDTO.getLingL());
            list.add(lingL);
        }
        if (StringUtils.isNotBlank(townDTO.getChiX())) {
            TownEntity chiX = new TownEntity("赤锡乡", townDTO.getChiX());
            list.add(chiX);
        }
        if (StringUtils.isNotBlank(townDTO.getWuT())) {
            TownEntity wuT = new TownEntity("梧桐镇", townDTO.getWuT());
            list.add(wuT);
        }
        if (StringUtils.isNotBlank(townDTO.getSongK())) {
            TownEntity songK = new TownEntity("嵩口镇", townDTO.getSongK());
            list.add(songK);
        }
        if (StringUtils.isNotBlank(townDTO.getFuK())) {
            TownEntity fuK = new TownEntity("洑口乡", townDTO.getFuK());
            list.add(fuK);
        }
        if (StringUtils.isNotBlank(townDTO.getGaiY())) {
            TownEntity gaiY = new TownEntity("盖洋乡", townDTO.getGaiY());
            list.add(gaiY);
        }
        if (StringUtils.isNotBlank(townDTO.getChangQ())) {
            TownEntity changQ = new TownEntity("长庆镇", townDTO.getChangQ());
            list.add(changQ);
        }
        if (StringUtils.isNotBlank(townDTO.getDongY())) {
            TownEntity dongY = new TownEntity("东洋乡", townDTO.getDongY());
            list.add(dongY);
        }
        if (StringUtils.isNotBlank(townDTO.getXiaB())) {
            TownEntity xiaB = new TownEntity("霞拔乡", townDTO.getXiaB());
            list.add(xiaB);
        }
        if (StringUtils.isNotBlank(townDTO.getTongA())) {
            TownEntity tongA = new TownEntity("同安镇", townDTO.getTongA());
            list.add(tongA);
        }
        if (StringUtils.isNotBlank(townDTO.getDaY())) {
            TownEntity daY = new TownEntity("大洋乡", townDTO.getDaY());
            list.add(daY);
        }
        if (StringUtils.isNotBlank(townDTO.getPanG())) {
            TownEntity panG = new TownEntity("盘谷乡", townDTO.getPanG());
            list.add(panG);
        }
        if (StringUtils.isNotBlank(townDTO.getHongX())) {
            TownEntity hongX = new TownEntity("红星镇", townDTO.getHongX());
            list.add(hongX);
        }
        if (StringUtils.isNotBlank(townDTO.getBaiY())) {
            TownEntity baiY = new TownEntity("白云乡", townDTO.getBaiY());
            list.add(baiY);
        }
        if (StringUtils.isNotBlank(townDTO.getDanY())) {
            TownEntity danY = new TownEntity("丹云乡", townDTO.getDanY());
            list.add(danY);
        }
        return list;
    }*/

    /**
     * 用进一法把两个整型相除得结果
     *
     * @param total
     * @param size
     * @return
     */
    public static Double intGetTotalPage(int total, int size) {
        return Math.ceil((double) total / (double) size);
    }

    /**
     * double保留两位小数
     *
     * @param math
     * @return
     */
    public static String doubleFormat(Double math) {
        DecimalFormat df = new DecimalFormat("#.##");
        String str = df.format(math);
        return str;
    }

    /**
     * 自定义保留位数
     * @param x  位数，2 两位 3 保留三位小数
     * @param num  需要保留的数字
     * @return
     */
    public static double keepNumberFormat(int x,double num)
    {

        BigDecimal bg = new BigDecimal(num);
        double numFormat = bg.setScale(x,BigDecimal.ROUND_HALF_UP).doubleValue();
        return  numFormat;
    }



    /**
     * 求最后得分
     *
     * @param score
     * @param weigth
     * @return
     */
    public static String getFinalScore(String score, String weigth) {
        Double sc = Double.valueOf(score);
        if(StringUtils.isBlank(weigth))
            weigth ="0.0";
        Double we = Double.valueOf(weigth) / 1000;
        Double finalScore = sc * we;
        return doubleFormat(finalScore);
    }

    /**
     * 属性复制器
     *
     * @param obj
     * @param obj2
     */
    public static void copyPro(Object obj, Object obj2) {
        try {
            BeanInfo soursebean = Introspector.getBeanInfo(obj.getClass(), Object.class);
            PropertyDescriptor[] sourpro = soursebean.getPropertyDescriptors();

            BeanInfo soursebean2 = Introspector.getBeanInfo(obj2.getClass(), Object.class);
            PropertyDescriptor[] sourpro2 = soursebean2.getPropertyDescriptors();
            for (int i = 0; i < sourpro.length; i++) {
                for (int j = 0; j < sourpro2.length; j++) {
                    if (sourpro[i].getName().equals(sourpro2[j].getName()) && sourpro[i].getPropertyType().equals(sourpro2[j].getPropertyType())) {
                        sourpro2[j].getWriteMethod().invoke(obj2, sourpro[i].getReadMethod().invoke(obj));
                        break;
                    }
                }
            }
        } catch (IntrospectionException e) {
            // TODO Auto-generated catch block
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * 对象比较器
     * @param obj1
     * @param obj2
     * @return
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     */
    public static int compareObject(Object obj1, Object obj2) throws ClassNotFoundException, IllegalAccessException {
        Class<?> cla1 = obj1.getClass();
        Class<?> cla2 = obj2.getClass();

        Field[] field1 = cla1.getDeclaredFields();//获取对象的属性列表
        Field[] field2 = cla2.getDeclaredFields();//

        for (int i = 0; i < field1.length; i++) {
            for (int j = 0; j < field2.length; j++) {
                if (field1[i].getName().equals(field2[j].getName())) {
                    if (field1[i].getName().equals(field2[j].getName())) {
                        field1[i].setAccessible(true);
                        field2[j].setAccessible(true);
                        //如果field1[i]属性值与field2[j]属性值内容不相同
                        if (!compare(field1[i].get(obj1), field2[j].get(obj2))) {
                            return 1;
                        }
                    }
                }
            }
        }
        return 0;
    }

    public static boolean compare(Object obj1, Object obj2) {
        if (obj1 == null && obj2 == null) {
            return true;
        }
        if (obj1 == null && obj2 != null) {
            if (obj1 == null && "".equals(obj2)) {
                return true;
            }
            if (obj2 == null && "".equals(obj1)) {
                return true;
            }
            return false;
        }
        if (obj1.equals(obj2)) {
            return true;
        }
        return false;
    }

    /**
     * 字符串转换为Double
     * @param s
     * @return
     */
    public static Double doubleParse(String s) {
        if (StringUtils.isNotBlank(s) ) {
            return Double.parseDouble(s);
        } else {
            return 0.0;
        }
    }

    /**
     * 判断是否是包括浮点型的数字
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    /**
     * 判断两个数组是否相同
     *
     * @param a
     * @param b
     * @return
     */
    public static boolean arrayEquals(Object[] a, Object[] b) {
        for (int i = 0; i != (a.length < b.length ? a.length : b.length); i++)
        {
            System.out.println("表头： "+a[i] + " : " + b[i]);
            if (!a[i].equals(b[i])) return false;
        }

        return true;
    }

    public static void write(String filename, InputStream in) {
        File file = new File(PATH);
        if (!file.exists()) {
            if (!file.mkdirs()) {// 若创建文件夹不成功
                System.out.println("Unable to create external cache directory");
            }
        }
        File targetfile = new File(PATH + filename);
        OutputStream os = null;
        try {
            os = new FileOutputStream(targetfile);
            int ch = 0;
            while ((ch = in.read()) != -1) {
                os.write(ch);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理指标序列处理成 map
     */
    public static HashMap<String,Object> getIndexIdMap(String str)
    {
        HashMap<String,Object> map = new HashMap<>();
        if(StringUtils.isNotBlank(str))
        {

            String[] indexarr = str.split(",");
            for (String item: indexarr)
            {
                map.put(item,item);
            }


        }
        return  map;
    }

    /**
     *  分隔号，转为string List
     * @param str
     * @return
     */
    public static List<String> strToList(String str)
    {
       List<String> list  = new ArrayList<>();
        if(StringUtils.isNotBlank(str))
        {

            String[] indexarr = str.split(",");
            for (String item: indexarr)
            {
               list.add(item);
            }


        }
        return  list;
    }

    /**
     *  分隔号，转为string List
     * @param str
     * @return
     */
    public static List<Long> strToListLong(String str)
    {
        List<Long> list  = new ArrayList<>();
        if(StringUtils.isNotBlank(str))
        {

            String[] indexarr = str.split(",");
            for (String item: indexarr)
            {
                list.add(Long.parseLong(item));
            }


        }
        return  list;
    }

    /**
     * 处理勾选状态
     */
    public static List<RolePerFilter> checkItem( List<RolePerFilter> list)
    {
        for (RolePerFilter item : list) {
            /**
             菜单勾选状态
             */
            List<String> checks = Util.strToList(item.getRoleRight());
            item.setCheckAllGroup(checks);
            /**
             * 勾选的指标集合
             */
            List<String> indexlist = Util.strToList(item.getIndexRight());
            item.setCheckAllindexGroup(indexlist);
            /**
             * 按钮权限
             */
            List<String> btnChecks = Util.strToList(item.getBtnRight());
            item.setBtnRights(btnChecks);

            List<String> cityIndex = Util.strToList(item.getCityIndex());
            item.setCheckCityGroup(cityIndex);

            List<String> departIndex = Util.strToList(item.getDepartIndex());
            item.setCheckUnitGroup(departIndex);

        }

        return  list;
    }



    public static TreeMap<String,String> yearmonth(String year)
    {
        String[] month ={"01","02","03","04","05","06",
                         "07","08","09","10","11","12"};

                TreeMap<String,String> map = new TreeMap<>();
        if(StringUtils.isNotBlank(year))
        {
           for(String str: month)
           {
               map.put(year+str,year+str);
           }

        }
        return  map;
    }


    /**
     * 数字保留位数
     * @param x 位数
     * @param number 需要格式化的字符串
     * @return
     */
    public static String formatNumber(int x,String number ) {
        String strNum = number;
        if (ObjectUtils.isNotBlank(number) ) {
            double dbNumber = doubleParse(number);
            BigDecimal bd = new BigDecimal(dbNumber);
            double num = bd.setScale(x, BigDecimal.ROUND_HALF_UP).doubleValue();
            strNum = num + "";

        }

    return strNum;
    }

    /**
     * 数字保留位数
     * @param x 位数
     * @param number 需要格式化的字符串
     * @return
     */
    public static String formatNumber(int x,double number ) {

           // double dbNumber = doubleParse(number);
            BigDecimal bd = new BigDecimal(number);
            double num = bd.setScale(x, BigDecimal.ROUND_HALF_UP).doubleValue();
           String  strNum = num + "";



        return strNum;
    }

    public static double formatNumberDouble(int x,double number ) {

        // double dbNumber = doubleParse(number);
        BigDecimal bd = new BigDecimal(number);
        double num = bd.setScale(x, BigDecimal.ROUND_HALF_UP).doubleValue();




        return num;
    }


    /**
     * 选项工具
     */
    public static  List<SelectOptionBean>  setSelectList(ExamQuestionFilter exam)
    {

        List<SelectOptionBean> list = new ArrayList<>();
        if(com.sirdc.modules.utils.StringUtils.isNotBlank(exam.getSelectA()))
        {
            SelectOptionBean bean = new SelectOptionBean("A","A:"+exam.getSelectA());

            list.add(bean);
        }

        if(com.sirdc.modules.utils.StringUtils.isNotBlank(exam.getSelectB()))
        {
            SelectOptionBean bean = new SelectOptionBean("B","B:"+exam.getSelectB());

            list.add(bean);
        }
        if(com.sirdc.modules.utils.StringUtils.isNotBlank(exam.getSelectC()))
        {
            SelectOptionBean bean = new SelectOptionBean("C","C:"+exam.getSelectC());

            list.add(bean);
        }
        if(com.sirdc.modules.utils.StringUtils.isNotBlank(exam.getSelectD()))
        {
            SelectOptionBean bean = new SelectOptionBean("D","D:"+exam.getSelectD());

            list.add(bean);
        }
        if(com.sirdc.modules.utils.StringUtils.isNotBlank(exam.getSelectE()))
        {
            SelectOptionBean bean = new SelectOptionBean("E","E:"+exam.getSelectE());

            list.add(bean);
        }
        if(com.sirdc.modules.utils.StringUtils.isNotBlank(exam.getSelectF()))
        {
            SelectOptionBean bean = new SelectOptionBean("F","F:"+exam.getSelectF());

            list.add(bean);
        }
        if(com.sirdc.modules.utils.StringUtils.isNotBlank(exam.getSelectG()))
        {
            SelectOptionBean bean = new SelectOptionBean("G","G:"+exam.getSelectG());

            list.add(bean);
        }


        return  list;
    }


    /**
     * 随机生成X个字符
     * @param x
     * @return
     */
    public static String randomChar(int x)
    {
        String str ="";
        for (int i = 0; i < x; i++) {
            char c = (char) (int) (Math.random() * 26 + 97);
            str =c+str;
        }
        return  str;
    }




}
